<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="问题标题" prop="title" label-width="68px">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入问题标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="问题描述" prop="description" label-width="68px">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入问题描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布人手机号" prop="phone" label-width="100px">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入发布人手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="问题发布时间" label-width="100px">
        <el-date-picker
          v-model="daterangePublishTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['space:ques:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['space:ques:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['space:ques:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['space:ques:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="quesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="问题ID" align="center" prop="id" />-->
      <el-table-column label="问题标题" align="center" prop="title" />
      <el-table-column label="问题描述" align="center" prop="description" />
      <el-table-column label="问题发布人" align="center" prop="publisher" />
      <el-table-column label="发布人手机号" align="center" prop="phone" />
      <el-table-column label="问题发布时间" align="center" prop="publishTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回答数量" align="center" prop="replyCount" />
      <el-table-column label="是否隐藏" align="center" prop="isHidden">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isHidden"/>
        </template>
      </el-table-column>
      <el-table-column label="置顶状态" align="center" prop="isTop">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isTop"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort">
        <template slot-scope="scope">
          <!-- 只有设置了排序值且大于0的才显示数字 -->
          <span v-if="scope.row.sort && scope.row.sort > 0">{{ scope.row.sort }}</span>
          <span v-else>-</span> <!-- 未排序的显示为短横线 -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['space:ques:edit']"
          >修改排序等</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-read"
            @click="handleRead(scope.row)"
            v-hasPermi="['space:ques:read']"
          >查看回答</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['space:ques:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改查看问题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="问题标题" prop="title">-->
<!--          <el-input v-model="form.title" placeholder="请输入问题标题" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="问题描述" prop="description">-->
<!--          <el-input v-model="form.description" placeholder="请输入问题描述" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="问题发布人" prop="publisher">-->
<!--          <el-input v-model="form.publisher" placeholder="请输入问题发布人" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="发布人手机号" prop="phone">-->
<!--          <el-input v-model="form.phone" placeholder="请输入发布人手机号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="问题发布时间" prop="publishTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.publishTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择问题发布时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="回答数量" prop="replyCount">-->
<!--          <el-input v-model="form.replyCount" placeholder="请输入回答数量" />-->
<!--        </el-form-item>-->
        <el-form-item label="是否隐藏" prop="isHidden">
          <el-select v-model="form.isHidden" placeholder="请选择是否隐藏">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="置顶状态" prop="isTop">
          <el-select v-model="form.isTop" placeholder="请选择置顶状态">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQues, getQues, delQues, addQues, updateQues } from "@/api/space/ques";

export default {
  name: "Ques",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查看问题表格数据
      quesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 排序时间范围
      daterangePublishTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        description: null,
        phone: null,
        publishTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();

    // 添加路由守卫，监听进入该路由时刷新数据
    this.$watch(
      '$route',
      (newRoute, oldRoute) => {
        // 当路由发生变化且目标是当前组件时刷新数据
        if (newRoute.path === '/space/ques') {
          this.getList();
        }
      }
    );
  },
  // 添加 activated 生命周期钩子，在组件被激活时刷新数据
  activated() {
    // 在使用 keep-alive 的情况下，从其他页面回到此页面时会触发
    this.getList();
  },
  // 在路由进入时也刷新数据
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 如果是从 answer 页面返回的，则刷新列表
      if (from.path === '/space/answer') {
        vm.getList();
      }
    });
  },
  methods: {
    /** 查询查看问题列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};

      if (null != this.daterangePublishTime && '' != this.daterangePublishTime) {
        this.queryParams.params["beginPublishTime"] = this.daterangePublishTime[0];
        this.queryParams.params["endPublishTime"] = this.daterangePublishTime[1];
      }

      listQues(this.queryParams).then(response => {
        let rows = response.rows;

        // 前端处理排序：首先按sort倒序排序，sort为0或null的按发布时间倒序
        rows.sort((a, b) => {
          // 如果两者都有sort值且不为0
          if (a.sort && b.sort && a.sort > 0 && b.sort > 0) {
            // sort值倒序排序（大的在前）
            return b.sort - a.sort;
          }
          // 如果a有sort值但b没有或为0
          else if (a.sort && a.sort > 0 && (!b.sort || b.sort === 0)) {
            return -1; // a排在前面
          }
          // 如果b有sort值但a没有或为0
          else if (b.sort && b.sort > 0 && (!a.sort || a.sort === 0)) {
            return 1; // b排在前面
          }
          // 都没有sort值或sort为0时，按发布时间倒序
          else {
            // 转换为时间对象进行比较
            const timeA = new Date(a.publishTime).getTime();
            const timeB = new Date(b.publishTime).getTime();
            return timeB - timeA; // 发布时间倒序
          }
        });

        this.quesList = rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        description: null,
        publisher: null,
        phone: null,
        publishTime: null,
        replyCount: null,
        isHidden: null,
        isTop: null,
        sort: null // 确保重置时排序值为null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePublishTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加查看问题";
    },
    /** 查看回答按钮操作 */
    handleRead(row) {
      // 直接跳转到回答页面，只携带必要的信息
      this.$router.push({
        path: '/space/answer',
        query: {
          quesId: row.id, // 传递问题ID
          quesTitle: row.title, // 传递问题标题
          replyCount: row.replyCount // 传递回答数量
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQues(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改查看问题";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保sort值为数字类型
          if (this.form.sort !== null && this.form.sort !== undefined) {
            this.form.sort = Number(this.form.sort);
          }

          if (this.form.id != null) {
            updateQues(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList(); // 更新后刷新列表
            });
          } else {
            addQues(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList(); // 新增后刷新列表
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除查看问题编号为"' + ids + '"的数据项？').then(function() {
        return delQues(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('space/ques/export', {
        ...this.queryParams
      }, `ques_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
